from fastapi import APIRouter,Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

router = APIRouter()

# 由于我们这里是子路由，在上一层的main.py中访问的，这晨的路由要以上一层main.py做相对路径
templates = Jinja2Templates(directory="templates")


@router.get("/items/{id}",response_class=HTMLResponse)
async def read_item(request: Request,id: str):
    return templates.TemplateResponse(
        request=request,
        name="item.html",
        context={"id": id}
    )


@router.get("/", response_class=HTMLResponse)
async def read_goods_index(request: Request):
    return templates.TemplateResponse(
        request=request,
        name="index.html",
        context={
            "request": request,
            "message": "欢迎到FastAPI模板示例",
            "goods_list": ["苹果","香蕉","橙子"]
        }
    )

@router.get("/goods/{goods_id}",response_class=HTMLResponse)
async def read_goods(request: Request,goods_id: int):
    goods_list = {
        1: {"name": "苹果", "price": 5.5},
        2: {"name": "香蕉", "price": 3.5},
        3: {"name": "橙子", "price": 4.5}
    }
    goods = goods_list.get(goods_id,{"name":"未知商品","price":0})
    return templates.TemplateResponse(
        request=request,
        name="goods.html",
        context={
            "request": request,
            "goods_id": goods_id,
            "goods": goods
        }
    )

@router.get("/user/{user_id}",response_class=HTMLResponse)
async def read_user(request: Request,user_id: int):
    is_admin = user_id == 1
    return templates.TemplateResponse(
        request=request,
        name="user.html",
        context={
            "request": request,
            "user_id": user_id,
            "is_admin": is_admin,
            "username": "管理员" if is_admin else "普通用户"
        }
    )